<template>
	<div style="height: 100%;overflow: hidden;">
		<!-- 面包屑导航区 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>用户管理</el-breadcrumb-item>
			<el-breadcrumb-item>用户列表</el-breadcrumb-item>
		</el-breadcrumb>

		<!-- 卡片视图区域 -->
		<el-card v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" style="height: 95.5%;overflow: hidden;">
			<el-row :gutter="20" style="height: 7%;">
				<el-col :span="6">
					<el-input placeholder="请输入内容" v-model="queryInfo.query">
						<el-button slot="append" icon="el-icon-search" @click="findUserList"></el-button>
					</el-input>
				</el-col>
				<el-col :span="4">
					<el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
				</el-col>
			</el-row>

			<template>
				<!-- 表格区域 -->
				<el-table :data="userlist" border stripe height="85%">
					<el-table-column type="index" label=""></el-table-column>
					<el-table-column prop="id" label="序号" v-show="false"></el-table-column>
					<el-table-column prop="username" label="姓名"></el-table-column>
					<el-table-column prop="email" label="邮箱"></el-table-column>
					<el-table-column prop="mobile" label="电话"></el-table-column>
					<el-table-column prop="role_name" label="角色"></el-table-column>
					<el-table-column prop="mg_state" label="状态">
						<template v-slot="scope">
							<el-switch v-model="scope.row.mg_state" @change="editStatus(scope.row)"></el-switch>
						</template>
					</el-table-column>
					<el-table-column prop="" label="操作" width="180px">
						<template v-slot="scope">
							<!-- 修改按钮 -->
							<el-button type="primary" icon="el-icon-edit" size="mini" @click="editUserInfo(scope.row)"></el-button>
							<!-- 删除按钮 -->
							<el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUserById(scope.row.id)"></el-button>
							<el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
								<!-- 分配权限按钮 -->
								<el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
							</el-tooltip>
						</template>
					</el-table-column>
				</el-table>

				<!-- 分页区域 -->
				<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum"
				 :page-sizes="[10, 15, 20, 25]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper"
				 :total="total" style="height: 7%;line-height: 100%;">
				</el-pagination>

				<!-- Diglog层 -->
				<el-dialog title="添加用户" :visible.sync="addDialogVisible" width="20%" @close="closeDialog('addRuleForm')">
					<el-form :rules="addRules" :model="addUserForm" ref="addRuleForm" label-width="70px">
						<el-form-item label="用户名" prop="username">
							<el-input v-model="addUserForm.username" autocomplete="off"></el-input>
						</el-form-item>
						<el-form-item label="密码" prop="password">
							<el-input v-model="addUserForm.password" type="text" auto-complete="off" @focus="changeType"></el-input>
						</el-form-item>
						<el-form-item label="邮箱号" prop="email">
							<el-input v-model="addUserForm.email"></el-input>
						</el-form-item>
						<el-form-item label="手机号" prop="mobile">
							<el-input v-model="addUserForm.mobile"></el-input>
						</el-form-item>
					</el-form>
					<!-- Diglog层底部区域 -->
					<div slot="footer" class="dialog-footer">
						<el-button @click="addDialogVisible = false">取 消</el-button>
						<el-button type="primary" @click="submitAddForm('addRuleForm')">新 增</el-button>
					</div>
				</el-dialog>
				
				<!-- Diglog层 -->
				<el-dialog title="添加用户" :visible.sync="editDialogVisible" width="20%" @close="closeDialog('editRuleForm')">
					<el-form :rules="editRules" :model="editUserForm" ref="editRuleForm" label-width="70px">
						<el-form-item label="用户名" prop="username">
							<el-input v-model="editUserForm.username" disabled></el-input>
						</el-form-item>
						<el-form-item label="邮箱号" prop="email">
							<el-input v-model="editUserForm.email"></el-input>
						</el-form-item>
						<el-form-item label="手机号" prop="mobile">
							<el-input v-model="editUserForm.mobile"></el-input>
						</el-form-item>
					</el-form>
					<!-- Diglog层底部区域 -->
					<div slot="footer" class="dialog-footer">
						<el-button @click="editDialogVisible = false">取 消</el-button>
						<el-button type="primary" @click="submitEditForm('editRuleForm')">修 改</el-button>
					</div>
				</el-dialog>
			</template>

		</el-card>
	</div>
</template>

<script>
	export default {
		data() {
			// 自定义验证手机号
			var checkPhone = (rule, value, callback) => {
				const phoneReg = /^1[3|4|5|7|8][0-9]{9}$/
				if (!value) {
					return callback(new Error('电话号码不能为空'))
				}
				setTimeout(() => {
					// Number.isInteger是es6验证数字是否为整数的方法,但是我实际用的时候输入的数字总是识别成字符串
					// 所以我就在前面加了一个+实现隐式转换

					if (!Number.isInteger(+value)) {
						callback(new Error('请输入数字值'))
					} else {
						if (phoneReg.test(value)) {
							callback()
						} else {
							callback(new Error('电话号码格式不正确'))
						}
					}
				}, 100)
			}
			// 自定义验证邮箱
			var checkEmail = (rule, value, callback) => {
				const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
				if (!value) {
					return callback(new Error('邮箱不能为空'))
				}
				setTimeout(() => {
					if (mailReg.test(value)) {
						callback()
					} else {
						callback(new Error('请输入正确的邮箱格式'))
					}
				}, 100)
			}
			return {
				queryInfo: {
					query: '',
					pagenum: 1,
					pagesize: 10
				},
				addUserForm: {
					username: '',
					password: '',
					mobile: '',
					email: ''
				},
				editUserForm: {
					username: '',
					mobile: '',
					email: '',
					id: ''
				},
				// 添加用户信息表单的验证
				addRules: {
					username: [{
							required: true,
							message: '请输入用户名',
							trigger: 'blur'
						},
						{
							min: 3,
							max: 8,
							message: '长度在 3 到 8 个字符',
							trigger: 'blur'
						}
					],
					password: [{
							required: true,
							message: '请输入密码',
							trigger: 'blur'
						},
						{
							min: 6,
							max: 12,
							message: '长度在 6 到 12 个字符',
							trigger: 'blur'
						}
					],
					email: [{
							required: true,
							validator: checkEmail, 
							trigger: 'blur'
						}
					],
					mobile: [{
							required: true,
							validator: checkPhone, 
							trigger: 'blur'
						}
					]
				},
				// 修改用户信息表单的验证
				editRules: {
					email: [{
							required: true,
							validator: checkEmail, 
							trigger: 'blur'
						}
					],
					mobile: [{
							required: true,
							validator: checkPhone, 
							trigger: 'blur'
						}
					]
				},
				userlist: [],
				total: 0,
				// 控制添加用户对话框的显示与隐藏
				addDialogVisible: false,
				loading: false,
				editDialogVisible: false
			}
		},
		// 加载触发的事件
		created() {
			this.getUserList()
		},
		// 方法集合
		methods: {
			// 获取所有用户信息
			async getUserList() {
				this.loading = true;
				const { data: result } = await this.$axios.get('users', {
					params: this.queryInfo
				});
				if (result.meta.status !== 200) {
					this.$message.error(result.meta.msg)
					return
				}
				setTimeout(() => {
					this.userlist = result.data.users;
					this.total = result.data.total;
					this.loading = false;
				},300)
			},
			// 监听 pagesize改变事件
			handleSizeChange(newSize) {
				this.queryInfo.pagesize = newSize;
				this.getUserList()
			},
			// 监听页码改变事件
			handleCurrentChange(newPage) {
				this.queryInfo.pagenum = newPage;
				this.getUserList()
			},
			// 监听switch组件的改变，用户状态修改
			async editStatus(userinfo) {
				// 调用服务器修改方法
				const { data: result } = await this.$axios.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
				if (result.meta.status !== 200) {
					this.$message.error('更新用户状态失败！');
					userinfo.mg_state = !userinfo.mg_state;
					return;
				}
				this.$message.success('更新用户状态成功！');
			},
			// 实现查询功能
			async findUserList() {
				// 解决页码不在第一页时搜索不到的bug
				this.queryInfo.pagenum = 1;
				// 重新查询
				this.getUserList();
			},
			// 添加用户提交事件
			async submitAddForm(ruleForm) {
				// 验证表单数据是否合法
				this.$refs[ruleForm].validate(async (valid) => {
					if (valid) {
						// 调用服务器添加方法
						const { data:result } = await this.$axios.post('users',this.addUserForm);
						if(result.meta.status !== 201){
							this.$message.error(result.meta.msg);
							return;
						}
						this.$message.success('添加用户成功！');
						// 重置表单
						this.$refs[ruleForm].resetFields();
						// 关闭弹窗
						this.addDialogVisible = false;
						// 最后一页的页数
						var num = this.total / this.queryInfo.pagesize;
						// 跳转到最后一页
						this.queryInfo.pagenum = /(^[1-9]\d*$)/.test(num) ? Math.ceil(num+1) : Math.ceil(num);
						// 重新查询
						this.getUserList();
					} else {
						return false;
					}
				})
			},
			// 打开修改用户弹窗，进行传值
			editUserInfo(row) {
				this.editUserForm.username = row.username;
				this.editUserForm.email = row.email;
				this.editUserForm.mobile = row.mobile;
				this.editUserForm.id = row.id;
				this.editDialogVisible = true
			},
			// 修改用户方法
			submitEditForm(ruleForm) {
				// 验证表单数据是否合法
				this.$refs[ruleForm].validate(async (valid) => {
					if (valid) {
						// 调用服务器更新方法
						const { data:result } = await this.$axios.put(`users/${this.editUserForm.id}`,this.editUserForm);
						if(result.meta.status !== 200){
							this.$message.error(result.meta.msg);
							return;
						}
						this.$message.success('修改用户成功！');
						// 重置表单
						this.$refs[ruleForm].resetFields();
						// 关闭弹窗
						this.editDialogVisible = false;
						// 重新查询
						this.getUserList();
					} else {
						return false;
					}
				})
			},
			// 按照ID删除用户
			deleteUserById(id) {
				this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
				  confirmButtonText: '确定',
				  cancelButtonText: '取消',
				  type: 'warning'
				}).then(async () => {
					// 确定删除
					const { data: result } = await this.$axios.delete("users/"+id);
					console.log(id);
					if(result.meta.status !== 200) {
						return this.$message.error(result.meta.msg);
					}
					// 删除成功
					this.$message.success("删除成功！");
					// 重新查询
					this.getUserList();
				}).catch(() => {
					// 取消删除
					this.$message.info("取消删除！");      
				});
			 },
			// 改变密码框的type为password
			changeType(e) {
				e.srcElement.type = 'password';
			},
			// 弹出层的关闭事件
			closeDialog(ruleForm) {
				// 重置表单
				this.$refs[ruleForm].resetFields();
			}
		
		}
	}
</script>

<style lang="less" scoped>
	.text {
		font-size: 14px;
	}

	.item {
		padding: 18px 0;
	}

	.box-card {
		width: 480px;
	}

	.el-table {
		margin: 10px 0;
		font-size: 14px;
		width: 100%;
		max-height:85%;
		overflow: auto;
	}

	.el-pagination {
		// margin-top: 12px;
	}
</style>
